#include "homepage.h"
#include "ui_homepage.h"
#include <QDebug>
HomePage::HomePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);
    count =1;
    //第一步：创建一个QBarSet对象；QBarSet类代表条形图中的一组条形
    datas = QVector<QBarSet*>();
    QBarSet *set0 = new QBarSet("紫外(分)",this);
    QBarSet *set1 = new QBarSet("光照(分)",this);
    QBarSet *set2 = new QBarSet("紫外(时)",this);
    QBarSet *set3 = new QBarSet("光照(时)",this);
    //第二步：创建一个QBarSeries对象，QBarSeries类将一系列数据显示为按类别分组的竖线
    for(int i =0 ;i<5;i++)
    {
        *set0<<rand()%10;
        *set1<<rand()%10;
        *set2<<rand()%10;
        *set3<<rand()%10;
    }
    datas.push_back(set0);
    datas.push_back(set1);
    datas.push_back(set2);
    datas.push_back(set3);
    series = new QBarSeries;
    series->append(datas.at(0));
    series->append(datas.at(1));
    series->append(datas.at(2));
    series->append(datas.at(3));
    series->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);  //设置标签显示的位置
    series->setLabelsVisible(true);  //设置数据标签可见
    //第三步：创建一个QChart用来装QBarSeries对象；
    //QChart是一个QGraphicsWidget，可以在QGraphicsScene中显示
    chart = new QChart;
    chart->addSeries(series);
    chart->setTitle("Simple barchart example");
    chart->setAnimationOptions(QChart::SeriesAnimations);

    //第四步：给柱状图添加一个坐标
    axis = new QBarCategoryAxis();
    getXAxis();
    chart->createDefaultAxes();  //创建一个默认的坐标轴
    chart->setAxisX(axis,series);//设置X坐标轴

    //第五步：创建一个QChartView来显示表格
    chartView = new QChartView(chart,this);
    chartView->resize(ui->tableWidget->width(),ui->tableWidget->height());

    box = new QHBoxLayout();
    box->addWidget(chartView);
    ui->tableWidget->setLayout(box);

}

HomePage::~HomePage()
{
    delete ui;
}

void HomePage::showBar()
{
    box->removeWidget(chartView);

    if(chartView!=NULL)
    {
        delete chartView;
    }
    datas.at(0)->remove(0);
//    datas.at(1)->remove(0);
//    datas.at(3)->remove(0);
//    datas.at(4)->remove(0);
//    chart->removeAllSeries();
    getXAxis();
    chart->setAxisX(axis,series);//设置X坐标轴;

    chartView = new QChartView(chart,this);
    chartView->resize(ui->tableWidget->width(),ui->tableWidget->height());
    box->addWidget(chartView);
}

void HomePage::getXAxis()
{
        QStringList categories;
        for(int i = 0;i<4;i++)
        {
            QString str;
            str= "第 " + QString::number(count+i) + "次";
            categories<<str;
        }
        count++;
        axis->clear();
        axis->append(categories);
}

void HomePage::on_updateButton_clicked()
{
    showBar();
}
